<!DOCTYPE html>
<html>
<head>
  <title>实时聊天室</title>
  <style>
    #login { margin: 20px; }
    #chat { display: none; }
    .message { margin: 5px; padding: 5px; border: 1px solid #ccc; }
  </style>
</head>
<body>
  <!-- 登录界面 -->
  <div id="login">
    <input type="text" id="username" placeholder="输入用户名">
    <button onclick="login()">进入聊天室</button>
    <div id="error" style="color: red;"></div>
  </div>
  <button onclick="logout()">退出聊天室</button>

  

  <!-- 聊天界面 -->
  <div id="chat">
    <div id="messages"></div>
    <input type="text" id="message" placeholder="输入消息">
    <button onclick="sendMessage()">发送</button>
  </div>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    const socket = io();
    let currentUser = '';

    // 连接事件处理
    socket.on('connect', () => {
      console.log('已连接到服务器');
    });

    // 登录逻辑
    function login() {
      const username = document.getElementById('username').value;
      if (!username) return;
      currentUser = username;
      socket.emit('join', username);
    }
    function logout() {
  socket.disconnect();
  alert('你已离开聊天室');
  window.location.href = '/'; // 回到登录页
}

    // 登录成功
    socket.on('login_success', () => {
      document.getElementById('login').style.display = 'none';
      document.getElementById('chat').style.display = 'block';
    });

    // 用户名错误
    socket.on('username_error', (msg) => {
      document.getElementById('error').innerText = msg;
    });

    // 发送消息
    function sendMessage() {
      const message = document.getElementById('message').value;
      if (message) {
        socket.emit('send_message', message);
        document.getElementById('message').value = '';
      }
    }

    // 接收消息
    socket.on('new_message', (data) => {
      const messages = document.getElementById('messages');
      messages.innerHTML += `<div class="message"><b>${data.user}:</b> ${data.text}</div>`;
    });

    // 用户加入/离开通知
    socket.on('user_joined', (username) => {
      addSystemMessage(`${username} 加入了聊天室`);
    });

    socket.on('user_left', (username) => {
      addSystemMessage(`${username} 离开了聊天室`);
    });

    function addSystemMessage(text) {
      const messages = document.getElementById('messages');
      messages.innerHTML += `<div style="color: gray;">${text}</div>`;
    }

    // 回车发送消息
    document.getElementById('message').addEventListener('keypress', (e) => {
      if (e.key === 'Enter') sendMessage();
    });
  </script>
</body>
</html>